
export class pub2sub{
    topics:Map<any,Map<string,Set<Function>>>=new Map();
    subscribe(topic:any, group:string, subscriber:Function) {
        let topics = this.topics;
        if (!topics.has(topic)) topics.set(topic, new Map());
        let groups = topics.get(topic);
        //ts-ignore
        if (!groups?.has(group)) groups?.set(group, new Set())
        let subscribers = groups?.get(group);
        subscribers?.add(subscriber);
    };
    notify(topic:any, group:string, info:any, unSubscribe:boolean) {
        let topics = this.topics;
        if (!topics.has(topic)) return;
        let groups = topics.get(topic);
        if (group && !groups?.has(group)) return;
        if (group) {
            [groups?.get(group)].forEach(subscribers => subscribers?.forEach(subscriber => {
                subscriber(info, group);
                if (unSubscribe) subscribers.delete(subscriber);
            }));;
        }else{
            groups?.forEach(subscribers => subscribers.forEach(subscriber => {
                subscriber(info, group);
                if (unSubscribe) subscribers.delete(subscriber);
            }));
        }
    };
    unSubscribe(topic:any, group:string, subscriber:Function) {
        let topics = this.topics;
        if (!topics.has(topic)) return;
        let groups = topics.get(topic);
        if (!groups?.has(group)) return;
        groups?.get(group)?.delete(subscriber);
    };
    clear(topic:any, group:string) {
        let topics = this.topics;
        if (!topics.has(topic)) return;
        if (!group) return topics.delete(topic);
        return topics?.get(topic)?.delete(group);
    };
    dispose() {
        this.topics.clear();
    }

constructor(){
}
}